package de.sendorian.app.forumArchive.dundjinni;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.filters.LinkStringFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;
import org.springframework.stereotype.Component;

import de.sendorian.app.forumArchive.domain.Forum;
import de.sendorian.app.forumArchive.finder.ForumFinder;


@Component
public class DundjinniForumFinder extends ForumFinder {

    private static final Logger LOG = Logger.getLogger(DundjinniForumFinder.class);


    public DundjinniForumFinder() {
    }


    public List<Forum> find(String url) {
        List<Forum> forums = new ArrayList<Forum>();
        NodeList nodeList = parse(url, buildEntryPageFilter(), true);
        String logMessage = "Found forums:\n";
        for (Node node : nodeList.toNodeArray()) {
            String link = ((TagNode) node).getAttribute("href");
            String linkName = node.getChildren().elementAt(0).getText();
            Forum forum = new Forum();
            forum.setName(linkName);
            forum.setUrl(link);
            forums.add(forum);
            logMessage += linkName + "\n";
        }
        LOG.trace(logMessage);
        return forums;
    }


    @Override
    protected NodeFilter buildEntryPageFilter() {
        NodeFilter filter = new LinkStringFilter("FID=8"); // Fantasy
        NodeFilter filter2 = new LinkStringFilter("FID=13"); // Contests
        NodeFilter filter3 = new LinkStringFilter("FID=14"); // SciFi
        NodeFilter filter4 = new LinkStringFilter("FID=15"); // Iso

        return new OrFilter(new NodeFilter[] { filter, filter2, filter3, filter4 });
        // return filter;
    }
}
